<?PHP
/*
	生成XML格式数据
	by iCer@2004/04/06 00:59:59 Beijing Time Zone
*/
/**
 * generate xml data-_-
 * 
 * @package  iforum.common
 * @author   iCer <iCer@justdn.com>
 * @version  $Id: Array2Xml.php,v 1.3 2005/04/06 04:07:55 icer Exp $
 */
class Array2Xml
{
	var $doc;
	var $charset;
	var $version;

	function Array2Xml($charset="utf-8", $version="1.0")
	{
		//echo $charset;
		$this->__construct($charset, $version);
	}

	function __construct($charset="utf-8", $version="1.0")
	{
		//$this->doc = new DOMIT_Document();
		$this->doc = new DOMDocument($version);
		//$this->doc->encoding = 'iso-8859-1';

		$this->charset = $charset;
		$this->version = $version;	
	}
	
	function parse($tag, $rs, $pi=false)
	{
		//append PI
		if (is_array($pi))
		{
			foreach ($pi as $p)
			{
				$this->doc->appendChild($this->doc->createProcessingInstruction($p[0],$p[1]));
			}
		}
		
		$this->doc->appendChild($this->parseArray($tag, $rs));
	}
	
	/**
	 * 把dom对象作为字符串输出
	 *
	 * @param string $target 输出目标~可以是流或者文件之类的地方,如"php://output"或"savedata.xml" 
	 * @return 
	 */
	function output($target='php://output')
	{
		$x = $this->doc->saveXML();
		echo htmldecode($x);
		//$this->doc->save($target);	
	}
	
	
	function &parseArray($tag, $rs)
	{
		//append data
		$node = &$this->doc->createElement($tag);
		if(!is_array($rs))
		{
			//$content = &$this->doc->createTextNode(iconv($this->charset, "utf-8", $rs));
			if(!is_int($rs))
			{
				//$content = &$this->doc->createTextNode(iconv($this->charset, "utf-8", $rs));
				$content = &$this->doc->createTextNode(iconv($this->charset, "utf-8", $rs));
			}
			else 
			{
				$content = &$this->doc->createTextNode(iconv($this->charset, "utf-8", $rs));
			}			
			
			$node->appendChild(&$content);
		}
		else
		{
			foreach($rs as $k=>$v)
			{
				$k=(is_int($k)?"item":$k);
				$child = &$this->doc->createElement($k);
				$node->appendChild($this->parseArray($k, $v));
			}
		}
		return $node;	
	}
}

?>